package com.superfish.cutieshop.utils;

import android.content.Context;

import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;
import com.superfish.cutieshop.BaseApp;
import com.superfish.cutieshop.BaseConfig;
import com.superfish.cutieshop.been.User;

import java.util.List;


/**
 * 处理个人用户的类 -- 校验下db是否需要判断为null
 **/
public class UserInfo {

    private Context mContext;

    private DbUtils mDB;

    private UserInfo(Context context) {
        this.mContext = context;
        BaseApp app = (BaseApp) mContext.getApplicationContext();
        mDB = app.createDb();
    }// 不可继承

    private User user;

    /**
     * 获取User
     **/
    public User getUser() {
        // 如果为null 则优先从数据库读取处理
        if (user == null) {
            List<User> list = null;
            try {
                list = mDB.findAll(User.class);
            } catch (DbException e) {
            }
            if (list != null && list.size() > 0)
                user = list.get(0);
        }
        //
        return user;
    }

    /**
     * 更新User
     **/
    public void setUser(User user) {
        this.user = user;
        try {
            if (user != null) {
                mDB.deleteAll(User.class);
                user.id = 0;
                // 不存在就保存
                mDB.save(user);
                LogTest.wlj("user存储成功了");
            } else {
                mDB.deleteAll(User.class);// 清空
            }
        } catch (Exception e) {
            LogTest.wlj("存储异常=" + e.toString());
        }
    }

    private static UserInfo mUserInfo;

    /**
     * 获取UserInfo
     **/
    public synchronized static UserInfo getInstense(Context context) {
        if (mUserInfo == null) {
            mUserInfo = new UserInfo(context);
        }
        return mUserInfo;
    }

    /**
     * 清理User信息
     **/
    public void clearUser() {
        try {
            mDB.deleteAll(User.class);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 存储token
     **/
    public void saveToken(String token) {
        if (token == null)
            token = "";
        PersistTool.saveString(BaseConfig.ShareKey.TOKEN, token);
    }

    /**
     * 获取token
     **/
    public String getToken() {
        return PersistTool.getString(BaseConfig.ShareKey.TOKEN, "");
    }

}
